#include "jlist.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static SListNode * s_pstCreateNode(void *pvData);

SList * JList_pstCreate()
{
	SList * pstList = (SList*)malloc(sizeof(SList));
	if(NULL == pstList) {
		printf("JList_pstCreate pstList malloc failed\n");
		return NULL;
	}

	SListNode *pstNode = s_pstCreateNode(NULL);

	pstList->m_pstHead = pstNode;
	pstList->m_pstTail = pstNode;
	pstList->m_iNum = 0;

	return pstList;
}

void JList_free(SList * pstList)
{
	if(NULL == pstList) {
		printf("JList_free NULL == pstList\n");
		return ;
	}

	SListNode *pstNode = pstList->m_pstHead;
	while (NULL != pstNode)
	{
		SListNode *pstTemp = pstNode;
		pstNode = pstNode->m_pstNext;
		free(pstTemp);
	}

	free(pstList);
}

int JList_add(SList * pstList, void * pvData)
{
	if(NULL == pstList) {
		printf("JList_add NULL == pstList\n");
		return -1;
	}

	SListNode *pstNode = s_pstCreateNode(pvData);
	pstList->m_pstTail->m_pstNext = pstNode;
	pstList->m_pstTail = pstNode;
	pstList->m_iNum++;
	return 0;
}

int JList_delIndex(SList * pstList, int iIndex)
{
	if(NULL == pstList) {
		printf("JList_delIndex NULL == pstList\n");
		return -1;
	}

	if(iIndex > pstList->m_iNum) {
		printf("JList_delIndex iIndex=%d, m_iNum=%d\n", iIndex, pstList->m_iNum);
		return -1;
	}

	SListNode * p = pstList->m_pstHead;
	SListNode * q = pstList->m_pstHead;
	for (int i=0; i<iIndex; i++)
	{
		q = p;
		p = p->m_pstNext;
	}
	q->m_pstNext = p->m_pstNext;
	free(p);

	return 0;
}

int JList_del(SList * pstList, SListNode * pstListNode)
{
	if(NULL == pstList || NULL == pstListNode) {
		printf("JList_del error input\n");
		return -1;
	}

    SListNode * q = pstList->m_pstHead;
    SListNode * p = pstList->m_pstHead->m_pstNext;
    while (NULL != p)
    {
        if(p == pstListNode)
        {
            q->m_pstNext = p->m_pstNext;
            free(p);
            break;
        }
        q = q->m_pstNext;
        p = p->m_pstNext;
    }

    return ( p==NULL ? -1 : 0 );
}

SListNode * JList_first(SList * pstList)
{
	if(NULL == pstList) {
		return NULL;
	}

	return pstList->m_pstHead->m_pstNext;
}

void JList_print(SList * pstList)
{
	SListNode * pstNode = pstList->m_pstHead->m_pstNext;
	while (NULL != pstNode)
	{
		printf("%d ", (int)pstNode->m_pvData);
		pstNode = pstNode->m_pstNext;
	}
	printf("\n");
}

static SListNode * s_pstCreateNode(void *pvData)
{
	SListNode *pstNode = (SListNode*)malloc(sizeof(SListNode));
	if(NULL == pstNode) {
		printf("s_pstCreateNode pstNode malloc failed\n");
		return NULL;
	}
	pstNode->m_pvData = pvData;
	pstNode->m_pstNext = NULL;
	return pstNode;
}








